package com.DosonLeung.homeschoolcommunication.Utils;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import com.DosonLeung.homeschoolcommunication.Constant.SystemConstant;
import com.DosonLeung.homeschoolcommunication.Constant.UrlConstant;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;

/**
 * Created by xujiachong on 14/11/24.
 */
public class UpdataUtil {

    private static AsyncHttpClient client;

    //file:需要上传的文件，请确保路径正确，name：你希望它上传到服务器后的名字，type:true为图片，false:为语音，handler:上传后发送上传结果
    public static void uploadFile(File file, String name,boolean type,Handler handler) {
        UpdataUtil.getToken(file, name,type, handler);
    }

    public static void getToken(final File file, final String name,final boolean type ,final Handler handler) {
        client = new AsyncHttpClient();
        String url = UrlConstant.getTokenUrl;
        RequestParams params = new RequestParams();
        params.put("key", name);
        client.post(url, params, new JsonHttpResponseHandler() {

            @Override
            public void onFinish() {
                // TODO Auto-generated method stub
                super.onFinish();
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers,
                                  JSONObject response) {
                try {
                    JSONObject obj = response.getJSONObject("data");
                    String token = obj.getString("uptoken");
                    UpdataUtil.uploadFileToSevenCow(token,file,type,name,handler);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                UpdataUtil.onFailure(name,type,handler);
            }
        });
    }

    private static void uploadFileToSevenCow(final String token, final File file,final boolean type, final String name,final Handler handler) {
        client = new AsyncHttpClient();
        String url = "http://upload.qiniu.com/";
        RequestParams params = new RequestParams();
        params.put("token", token);
        params.put("key", name);
        try {
            params.put("file", file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        client.post(url, params, new JsonHttpResponseHandler() {

            @Override
            public void onFinish() {
                // TODO Auto-generated method stub
                super.onFinish();
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers,
                                  JSONObject response) {
                UpdataUtil.onSuccess(name,type,handler);
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                UpdataUtil.onFailure(name,type,handler);
            }
        });
    }

    /**
     * Just write this method
     * type:图片true 声音 false
     */
    public static void onSuccess(String name,boolean type,Handler handler) {
        Message msg = new Message();
        Bundle bundle = new Bundle();
        bundle.putString("name",name);
        msg.setData(bundle);
        if(type)
            msg.what = SystemConstant.UPLOAD_IMAGE_SUCCESS;
        else
            msg.what = SystemConstant.UPLOAD_AUDIO_SUCCESS;
        handler.sendMessage(msg);
    }

    /**
     * Just write this method
     */
    public static void onFailure(String name,boolean type,Handler handler) {
        Message msg = new Message();
        Bundle bundle = new Bundle();
        bundle.putString("name",name);
        msg.setData(bundle);
        if(type)
            msg.what = SystemConstant.UPLOAD_IMAGE_FAIL;
        else
            msg.what = SystemConstant.UPLOAD_AUDIO_FAIL;
        handler.sendMessage(msg);
    }

    public static void stop(){
        if(client!=null) {
            client.cancelAllRequests(true);
            client = null;
        }
    }
}
